package com.bcfrj.shop.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUtils {
    @Value("${web.upload-path}")
    private static String uploadPath;
    public static String saveFile(MultipartFile uploadFile, HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String format = sdf.format(new Date());
        // 对上传的文件重命名，避免文件重名
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        try{
            uploadFile.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + format + newName;
            return filePath;
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return "noPath";
    }

}
